import React, {PureComponent} from "react";
import {Icon, Popconfirm, Table, Tooltip} from "antd";
import {connect} from "react-redux";
import {paginationProps, tableProps} from "../../lib/ui";
import {del, query, showEdit} from "./actions";
import moment from "moment";
import {getCurrentOrganization, getLastFilter, getPrincipal} from "../../lib/identity";
import {Resizable} from 'react-resizable';
import {getCarrierList, getClientList, organizations} from "../home/actions";
import {autoWidthColumns} from "../../lib/func";

const LAST_FILTER = "containerOrder";

const ResizeableTitle = props => {
    const {onResize, width, ...restProps} = props;

    if (!width) {
        return <th {...restProps} />;
    }

    return (
        <Resizable
            width={width}
            height={0}
            onResize={onResize}
            draggableOpts={{enableUserSelectHack: false}}
        >
            <th {...restProps} />
        </Resizable>
    );
};

class List extends PureComponent {
    state = {
        columns: [
            {
                title: "业务编号",
                dataIndex: "businessNumber",
                width: 180,
                render: (text, record) => (
                    <a
                        onClick={() => {
                            this.handleShowEdit(record);
                        }}
                    >
                        {text}
                    </a>
                )
            }, {
                title: "所属机构",
                dataIndex: "organizationName",
                width: 100,
                ellipsis: true,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "客户",
                dataIndex: "clientName",
                width: 100,
                ellipsis: true,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "柜号",
                dataIndex: "cabinetNumber",
                width: 200,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "国际班列单号",
                dataIndex: "orderNumber",
                width: 200,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "柜型",
                dataIndex: "cabinetType",
                width: 150,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "提箱日期",
                dataIndex: "pickDate",
                width: 100,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "提箱码",
                dataIndex: "pickNumber",
                width: 180,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "还箱剩余天数",
                dataIndex: "lessReturnDays",
                width: 120,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "预计还箱日期",
                dataIndex: "preReturnDate",
                width: 180,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "实际还箱日期",
                dataIndex: "actReturnDate",
                width: 180,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "超期天数",
                dataIndex: "beyondDays",
                width: 80,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "用箱天数",
                dataIndex: "useDays",
                width: 80,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "还箱地",
                dataIndex: "returnPlace",
                width: 180,
                ellipsis: true,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "还箱状态",
                dataIndex: "packageTypeName",
                width: 100,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "还箱令",
                dataIndex: "returnCommand",
                width: 180,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }, {
                title: "创建时间",
                dataIndex: "createTime",
                width: 180,
                render: text => <Tooltip placement="top" title={text}>{text}</Tooltip>
            }
        ]
    };
    onPageChange = (page, pageSize) => {
        const {dispatch, filter} = this.props;
        dispatch(query({
            "userId": getPrincipal().id,
            "organizationId": getCurrentOrganization(), ...filter,
            page,
            pageSize
        }));
    };

    handleShowEdit = row => {
        const {dispatch} = this.props;
        dispatch(showEdit(row));
    };

    handleDelete = id => {
        const {dispatch, page, pageSize, filter} = this.props;
        dispatch(del(id)).then(() => {
            dispatch(query({
                "userId": getPrincipal().id,
                "organizationId": getCurrentOrganization(), ...filter,
                page,
                pageSize
            }));
        });
    };


    componentWillMount() {
        const {dispatch, page, pageSize} = this.props;
        dispatch(organizations(getPrincipal().id));
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        dispatch(query({
            "userId": getPrincipal().id,
            "organizationId": getCurrentOrganization(), ...fields,
            page,
            pageSize
        }));
        dispatch(getClientList(getCurrentOrganization()));
        dispatch(getCarrierList(getCurrentOrganization()));
    };

    setRowClassName = (record) => {
        if (record.packageType === "UN_RETURN") {
            return 'table-color-send-no-finish';
        } else if (record.lock === true) {
            // 集装箱界面均为灰色
            return 'table-color-send-finish';
        }
    }

    handleResize = index => (e, {size}) => {
        this.setState(({columns}) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };
            return {columns: nextColumns};
        });
    };

    components = {
        header: {
            cell: ResizeableTitle,
        },
    };

    render() {
        const {
            page,
            pageSize,
            totalElements,
            dataSource,
            loading,
        } = this.props;
        const columns = this.state.columns;
        if (getPrincipal().admin) {
            const found = columns.find(item => item.title === '功能');
            if (!found) {
                columns.push(
                    {
                        title: '功能',
                        dataIndex: '',
                        key: '',
                        width: 50,
                        align: 'center',
                        fixed: 'right',
                        render: (text, record) => <span>
                    <Popconfirm title="确定删除此集装箱记录?" okText="是" cancelText="否"
                                onConfirm={() => this.handleDelete(record.id)}>
                        <Icon type="delete"/>
                    </Popconfirm>
                </span>,
                    }
                );
            }

        }
        const resizeColumns = columns.map((col, index) => ({
            ...col,
            onHeaderCell: column => ({
                width: column.width,
                onResize: this.handleResize(index),
            }),
        }));
        const tablePagination = {
            ...paginationProps,
            total: totalElements,
            current: page,
            pageSize: pageSize,
            onShowSizeChange: (current, newSize) =>
                this.onPageChange && this.onPageChange(1, newSize),
            onChange: this.onPageChange
        };

        return (
            <Table
                {...tableProps}
                bordered
                columns={resizeColumns}
                components={this.components}
                scroll={{x: 1500, y: 'calc(100vh - 430px)'}}
                pagination={tablePagination}
                dataSource={dataSource}
                loading={loading}
                rowClassName={this.setRowClassName}
            />
        );
    }
}

const
    mapStateToProps = state => {
        return {
            ...state.containerOrder.list
        };
    };

export default connect(mapStateToProps)(List);
